package com.ruoyi.web.controller.order;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ExcelMergeUtil;
import com.ruoyi.common.utils.OConvertUtils;
import com.ruoyi.order.domain.ExportOrderVo;
import com.ruoyi.order.domain.OrderInfo;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.order.domain.TbProductOrder;
import com.ruoyi.order.service.ITbProductOrderService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 订单Controller
 * 
 * @author ruoyi
 * @date 2025-08-19
 */
@RestController
@RequestMapping("/product/order")
public class TbProductOrderController extends BaseController
{
    @Autowired
    private ITbProductOrderService tbProductOrderService;

    /**
     * 查询订单列表
     */
    @PreAuthorize("@ss.hasPermi('product:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(TbProductOrder tbProductOrder)
    {
        startPage();
        List<TbProductOrder> list = tbProductOrderService.selectTbProductOrderList(tbProductOrder);
        return getDataTable(list);
    }



    @GetMapping("/appList")
    public TableDataInfo appList(TbProductOrder tbProductOrder)
    {
        startPage();
        LoginUser loginUser =this.getLoginUser();
        tbProductOrder.setCreateUserId(loginUser.getUserId());
        List<TbProductOrder> list = tbProductOrderService.selectTbProductOrderList(tbProductOrder);
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('product:order:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TbProductOrder tbProductOrder)
    {
        List<TbProductOrder> list = tbProductOrderService.selectTbProductOrderList(tbProductOrder);
        ExcelUtil<TbProductOrder> util = new ExcelUtil<TbProductOrder>(TbProductOrder.class);
        util.exportExcel(response, list, "订单数据");
    }


    @PreAuthorize("@ss.hasPermi('product:order:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/exportResult")
    public void exportResult(HttpServletResponse response, TbProductOrder tbProductOrder)
    {
        try{
            List<ExportOrderVo> exportOrderVos = tbProductOrderService.selectExportVo(tbProductOrder);

            // 2. 定义导出参数
            String[] titles = {"日期", "国家", "名称", "产品细节","金额","追踪单号"};
            String[] fieldNames = {"createTime", "country", "userName", "productDetails", "money", "tradeId"};
            String fileName = "业绩汇总表导出";
            int[] mergeColumns = {0,1,3,4,5}; // 需要合并的列索引（这里只合并部门列）
            ExcelMergeUtil.exportWithMerge(response,exportOrderVos,titles,fieldNames,fileName,mergeColumns);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @PostMapping("/exportWord")
    public void exportWord(HttpServletResponse response,TbProductOrder tbProductOrder) throws IOException {
        String content = tbProductOrderService.buildWorkContent(tbProductOrder, tbProductOrder.getTemplateId());
        String[] lines = content.split("\n");
        // 创建Word文档
        XWPFDocument document = new XWPFDocument();
        // 创建标题
        for (String line : lines) {
            XWPFParagraph paragraph = document.createParagraph();
            XWPFRun run = paragraph.createRun();
            run.setText(line);
            run.addBreak();
        }
        // 将文档写入ByteArrayOutputStream
        // 写入响应流
        try (OutputStream os = response.getOutputStream()) {
            document.write(os);
            os.flush();
        } finally {
            document.close();
        }
    }
    /**
     * 获取订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('product:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tbProductOrderService.selectTbProductOrderById(id));
    }

    /**
     * 新增订单
     */
    @PreAuthorize("@ss.hasPermi('product:order:add')")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TbProductOrder tbProductOrder)
    {
        return toAjax(tbProductOrderService.insertTbProductOrder(tbProductOrder));
    }

    /**
     * 修改订单
     */
    @PreAuthorize("@ss.hasPermi('product:order:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TbProductOrder tbProductOrder)
    {
        if (OConvertUtils.isNotEmpty(tbProductOrder) && tbProductOrder.getStatus() == 1){
            tbProductOrder.setConfirmTime(new Date());
        }
        return toAjax(tbProductOrderService.updateTbProductOrder(tbProductOrder));
    }

    /**
     * 删除订单
     */
    @PreAuthorize("@ss.hasPermi('product:order:remove')")
    @Log(title = "订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tbProductOrderService.deleteTbProductOrderByIds(ids));
    }

    @PostMapping("/createOrder")
    public AjaxResult createOrder(@RequestBody OrderInfo orderInfo)
    {
        LoginUser loginUser = this.getLoginUser();
        String nickName = loginUser.getUser().getNickName();
        orderInfo.setCreateBy(nickName);
        orderInfo.setCreateUserId(loginUser.getUserId());
        return toAjax(tbProductOrderService.createOrder(orderInfo));
    }


    @PostMapping("/editOrder")
    public AjaxResult editOrder(@RequestBody OrderInfo orderInfo)
    {
        LoginUser loginUser = this.getLoginUser();
        String nickName = loginUser.getUser().getNickName();
        orderInfo.setCreateBy(nickName);
        tbProductOrderService.editOrder(orderInfo);
        return AjaxResult.success();
    }
}
